import router from '@/router'

// 缓存滚动位置
document.addEventListener(
  'scroll',
  (e) => {
    if (e.target instanceof HTMLElement) {
      e.target.dataset.cacheScrollTop = e.target.scrollTop.toString()
      e.target.dataset.cacheScrollLeft = e.target.scrollLeft.toString()
    }
  },
  true,
)

// 还原滚动位置
export const restoreScroll = (target = document.documentElement) => {
  target.querySelectorAll('[data-cache-scroll-top]').forEach((el) => {
    const htmlEl = el as HTMLElement
    htmlEl.scrollTop = Number(htmlEl.dataset.cacheScrollTop) || 0
    htmlEl.scrollLeft = Number(htmlEl.dataset.cacheScrollLeft) || 0
  })
  if (target.hasAttribute('data-cache-scroll-top')) {
    target.scrollTop = Number(target.dataset.cacheScrollTop) || 0
    target.scrollLeft = Number(target.dataset.cacheScrollLeft) || 0
  }
}

// 重置滚动位置
export const resetScroll = (target = document.documentElement) => {
  target.querySelectorAll('[data-cache-scroll-top]').forEach((el) => {
    el.scrollTop = 0
    el.scrollTop = 0
  })
  if (target.hasAttribute('data-cache-scroll-top')) {
    target.scrollTop = 0
    target.scrollLeft = 0
  }
}

router.afterEach(async () => {
  await nextTick()
  restoreScroll()
})
